<template>
  <el-card class="box-card" v-loading="loading">
    <template #header>
      <div class="card-header">
        <span>高考头条</span>
      </div>
    </template>
    <div style="display: flex; justify-content: space-between">
      <div class="search">
        <el-select
          v-model="reqData.source"
          placeholder="请输入内容"
          size="large"
          clearable
          style="width: 240px; margin-right: 20px"
          @change="changeSelect"
        >
          <el-option
            v-for="item in filterPlatformList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-select
          v-model="reqData.recommend"
          placeholder="请输入内容"
          size="large"
          clearable
          style="width: 240px; margin-right: 20px"
          @change="changeSelect"
        >
          <el-option
            v-for="item in newDataList"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-input
          v-model="reqData.keywords"
          style="max-width: 300px"
          clearable
          placeholder="关键词"
          class="height40"
          @change="changeSelect"
        >
          <template #append>
            <el-button type="primary" @click="handleSearch">搜索</el-button>
          </template>
        </el-input>
      </div>

      <el-button type="primary" class="height40" @click="handleAddNew"
        >添加资讯</el-button
      >
    </div>
    <el-table
      :data="newList"
      style="width: 100%"
      class="margintop"
      stripe
      :header-cell-style="{ 'border-bottom': 'none' }"
      :header-row-style="{ height: '60px' }"
      :cell-style="{ height: '60px', 'border-bottom': 'none' }"
    >
      <el-table-column prop="sortVisible" label="排序" width="80px">
        <template #default="scope">
          <el-popover
            :popper-style="{ width: '50' }"
            placement="top-start"
            trigger="click"
            v-if="scope.row.sortVisible"
          >
            <div class="popover">
              <el-input-number
                v-model="scope.row.order"
                :min="0"
                @change="handleChange"
              />
              <p class="poverBtn" @click="sortBtn(scope.row)">确定</p>
            </div>
            <template #reference>
              <p style="cursor: pointer" @click="sort(scope.row)">
                {{ scope.row.order }}
              </p>
            </template>
          </el-popover>
          <p v-else style="cursor: pointer" @click="sort(scope.row)">
            {{ scope.row.order }}
          </p>
        </template>
      </el-table-column>
      <el-table-column prop="title" label="标题" />
      <el-table-column prop="source" label="平台管理" />
      <el-table-column label="推荐" width="120">
        <template #default="scope">
          <span>{{ NEWLIST[scope.row.recommend] ?? '-' }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="update_time" label="创建时间" width="200" />
      <el-table-column label="状态" width="80px">
        <template #default="scope">
          <el-tooltip
            class="box-item"
            effect="dark"
            placement="top"
            v-if="scope.row.stroeId == 0"
          >
            <el-switch
              @change="changeSwith(scope.row)"
              :disabled="scope.row.stroeId == 0"
              v-model="scope.row.status"
              :style="switchStyle(scope.row)"
            />
            <template #content>平台收录，不允许修改</template>
          </el-tooltip>
          <div v-else>
            <el-switch
              @change="changeSwith(scope.row)"
              :disabled="scope.row.stroeId == 0"
              v-model="scope.row.status"
              :style="switchStyle(scope.row)"
            />
          </div>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200">
        <template #default="scope">
          <div v-if="!scope.row.stroeId == 0">
            <el-tooltip
              class="box-item"
              effect="dark"
              content="编辑"
              placement="top"
            >
              <el-icon
                size="20"
                style="cursor: pointer"
                @click="editChange(scope.row)"
                ><EditPen
              /></el-icon>
            </el-tooltip>
            <el-tooltip
              class="box-item"
              effect="dark"
              content="删除"
              placement="top"
            >
              <el-icon
                @click="handleDelete(scope.row)"
                size="20"
                style="cursor: pointer; margin-left: 10px"
                ><Delete
              /></el-icon>
            </el-tooltip>
          </div>
        </template>
      </el-table-column>
    </el-table>
    <!-- <pagination
      v-show="total > 0"
      v-model:page=""
      v-model:limit=""
      :total="total"
      :background="false"
      @pagination="fetchNewsList"
    ></pagination> -->
    <el-pagination
      style="margin-top: 20px"
      v-model:current-page="reqData.page"
      v-model:page-size="reqData.pageSize"
      :page-sizes="[10, 20, 30]"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total ?? 0"
      @size-change="handleSizeChange"
      @current-change="handleCurrentChange"
    />
  </el-card>
</template>
<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { getNewsList, newsDel, newsSave } from '@/api/newsList/newsList';
const { proxy } = getCurrentInstance();
import { ElMessage } from 'element-plus';
const loading = ref(false);
const router = useRouter();
const total = ref(0);
const reqData = ref({
  pageSize: 10,
  page: 1,
  keywords: '',
  order: '',
  status: '',
  source: 2,
  recommend: '',
});
const newList = ref([]);
const filterPlatformList = ref([
  {
    value: 0,
    label: '全部',
  },
  {
    value: 1,
    label: '平台管理',
  },
  {
    value: 2,
    label: '自编新闻',
  },
]);
const newDataList = ref([
  {
    value: 0,
    label: '日常新闻',
  },
  {
    value: 1,
    label: '热门关注',
  },
  {
    value: 2,
    label: '横幅新闻',
  },
  {
    value: 3,
    label: '推荐新闻',
  },
]);
const NEWLIST = {
  0: '日常新闻',
  1: '热门关注',
  2: '横幅新闻',
  3: '推荐新闻',
};
const switchStyle = () => {
  // 正常状态样式
  return {
    '--el-switch-on-color': 'var(--el-color-primary)', // 开启颜色
    '--el-switch-off-color': '#909399', // 关闭颜色
  };
};
const changeSelect = () => {
  reqData.value.page = 1;
  fetchNewsList();
};
function editChange(rowData) {
  router.push({
    path: '/operation/headline',
    query: { id: rowData.id },
  });
}
const handleSizeChange = (val) => {
  reqData.value.pageSize = val;
  fetchNewsList();
};
const handleCurrentChange = (val) => {
  reqData.value.page = val;
  fetchNewsList();
};
const sortBtn = async (val) => {
  val.sortVisible = false;
  const data = await newsSave({ order: val.order, id: val.id });
  ElMessage({
    message: data.msg,
    type: 'success',
  });
  fetchNewsList();
};
const sort = (val) => {
  if (val.stroeId == 0) {
    newList.value = newList.value.map((v) => {
      if (v.id === val.id) {
        return { ...v, sortVisible: false }; // 返回一个新的对象，修改 sortVisible 属性
      }
      return v; // 其他元素保持不变
    });
  }
};
const handleChange = (val) => {
  reqData.value.num = val;
};

// 关键词搜索
const handleSearch = () => {
  reqData.page = 1;
  reqData.pageSize = 20;
  fetchNewsList();
};
const handleDelete = (rowData) => {
  proxy.$modal
    .confirm(`确认删除?`)
    .then(function () {
      return handleEewsDel(rowData.id);
    })
    .catch(() => {});
};
const handleEewsDel = (id) => {
  newsDel({ id }).then((res) => {
    if (res.code == 20000) {
      fetchNewsList();
      proxy.$modal.msgSuccess(res.msg);
    }
  });
};
const changeSwith = async (row) => {
  const updatedStatus = row.status ? 1 : 0; // 转换为后端需要的值
  const data = await newsSave({ status: updatedStatus, id: row.id });
  ElMessage({
    message: data.msg,
    type: 'success',
  });
  fetchNewsList();
};
const fetchNewsList = () => {
  loading.value = true;
  getNewsList(reqData.value)
    .then((res) => {
      if (res.code == 20000) {
        total.value = res.data.total;
        newList.value = res.data.data.map((item) => ({
          ...item,
          sortVisible: true, // 动态添加
          status: item.status == 1 ? true : false, // 转为 true 或 false
        }));

        loading.value = false;
      } else {
        loading.value = false;
      }
    })
    .catch(() => {
      loading.value = false;
    });
};

const handleAddNew = () => {
  router.push('/operation/headline');
};
onMounted(() => {
  fetchNewsList();
});
</script>
<style lang="scss" scoped>
:deep(.el-form--inline .el-form-item) {
  margin-right: 7px;
}
.poverBtn {
  cursor: pointer;
  margin-top: 10px;
  color: #165dff;
  font-size: 14px;
  display: flex;
  flex-direction: row;
  justify-content: right;
}
.search {
  display: flex;
  margin-right: 20px;
}
:deep(.el-form-item--default) {
  margin-bottom: 4px;
}
.box-card {
  margin: 20px;

  .card-header {
    font-size: 20px;
    font-weight: 600;
    color: #1d2129;
    padding: 10px;
    .headerSize {
      color: #4e5969;
      font-size: 14px;
      margin-left: 12px;
      font-weight: 400;
      height: 20px;
      line-height: 21px;
    }
  }
}
</style>
